package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {
    @Reference
    private ContractService contractService;

    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/list", name = "查询购销合同列表")
    public String findAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        User user = getUser();
        Integer degree = user.getDegree();
        if (degree == 4) {
            criteria.andCreateByEqualTo(user.getId());
        } else if (degree == 3) {
            criteria.andCreateDeptEqualTo(user.getDeptId());
        } else if (degree == 2) {
            criteria.andCreateDeptLike(user.getDeptId() + "%");
        }

        criteria.andCompanyIdEqualTo(getCompanyId());
        example.setOrderByClause("create_time desc");
        PageInfo pageInfo = contractService.findAll(example, page, pageSize);
        request.setAttribute("page", pageInfo);
        return "cargo/contract/contract-list";
    }

    @RequestMapping(value = "/toAdd", name = "跳转到新增购销合同页面")
    public String toAdd() {
        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/edit", name = "保存合同信息")
    public String save(Contract contract) {
        if (StringUtils.isEmpty(contract.getId())) {
            contract.setState(0);

            contract.setId(UUID.randomUUID().toString());
            contract.setCreateBy(getUser().getId());
            contract.setCreateDept(getUser().getDeptId());

            contract.setCreateTime(new Date());
            contract.setCreateDept(getUser().getDeptId());
            contract.setCompanyId(getCompanyId());
            contract.setCompanyName(getCompanyName());
            contractService.save(contract);
        } else {
            contract.setUpdateTime(new Date());

            contract.setUpdateBy(getUser().getId());
            contractService.update(contract);
        }

        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/toUpdate", name = "跳转到修改购销合同页面")
    public String toUpdate(String id) {
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-update";
    }

    @RequestMapping(value = "/submit", name = "提交购销合同")
    public String submit(String id) {
        // 直接更新已变化的值可以省去一次查询，减少数据库访问压力
        // Contract contract = contractService.findById(id);
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/cancel", name = "取消购销合同")
    public String cancel(String id) {
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/toView", name = "查看购销合同")
    public String toView(String id) {
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-view";
    }

    // 需要删除合同下的产品及产品附件信息
    @RequestMapping(value = "/delete", name = "删除购销合同")
    public String delete(String id) {
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/print", name = "跳转到出库表导出页面")
    public String toPrint(String id) {
        return "cargo/print/contract-print";
    }

    @RequestMapping(value = "/printExcel", name = "导出出库表")
    public void printExcel(String inputDate) throws IOException {
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoByShipTime(inputDate, getCompanyId());

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("出库表");
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        Row row = sheet.createRow(0);
        // 设置行高
        row.setHeightInPoints(36);
        Cell cell = row.createCell(1);
        String dateStr = inputDate.replaceAll("-0", "年").replaceAll("-", "年");
        cell.setCellValue(dateStr + "月出库表");
        cell.setCellStyle(bigTitle(workbook));

        // 设置表头（第2行标题）
        Row row2 = sheet.createRow(1);
        // 调整列宽
        sheet.setColumnWidth(1,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(2,16*256);
        sheet.setColumnWidth(3,26*256);
        sheet.setColumnWidth(4,16*256);
        sheet.setColumnWidth(5,16*256);
        sheet.setColumnWidth(6,16*256);
        sheet.setColumnWidth(7,16*256);
        sheet.setColumnWidth(8,16*256);

        String[] title = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        // 设置表头（第2行标题）
        row = sheet.createRow(1);
        row.setHeightInPoints(26);
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i + 1);
            cell.setCellValue(title[i]);
            cell.setCellStyle(title(workbook));
        }

        for (int i = 0; i < contractProductVoList.size(); i++) {
            row = sheet.createRow(i+2);
            row.setHeightInPoints(20);
            ContractProductVo contractProductVo = contractProductVoList.get(i);

            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
            cell.setCellStyle(text(workbook));
            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(text(workbook));
            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(text(workbook));
            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(text(workbook));
            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(text(workbook));
            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()));
            cell.setCellStyle(text(workbook));
            cell = row.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()));
            cell.setCellStyle(text(workbook));
            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());
            cell.setCellStyle(text(workbook));
        }
        // 导出workbook
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出库表.xlsx");

    }

    @RequestMapping(value = "/printExcelTemplate", name = "使用模板导出出库表")
    public void printExcelTemplate(String inputDate) throws IOException {
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoByShipTime(inputDate, getCompanyId());

        String templatePath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        Workbook workbook = new XSSFWorkbook(new FileInputStream(templatePath));
        Sheet sheet = workbook.getSheetAt(0);

        // 写入表头标题
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(1);
        String dateStr = inputDate.replaceAll("-0", "年").replaceAll("-", "年");
        cell.setCellValue(dateStr + "月份出库表");

        // 读取样式
        CellStyle[] cellStyles = new CellStyle[8];
        row = sheet.getRow(2);
        for (int i = 0; i < 8; i++) {
            cellStyles[i] = row.getCell(i + 1).getCellStyle();
        }

        // 向表格写入数据
        for (int i = 0; i < contractProductVoList.size(); i++) {
            row = sheet.createRow(i+2);
            row.setHeightInPoints(20);
            ContractProductVo contractProductVo = contractProductVoList.get(i);

            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
            cell.setCellStyle(cellStyles[0]);
            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(cellStyles[1]);
            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(cellStyles[2]);
            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(cellStyles[3]);
            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(cellStyles[4]);
            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()));
            cell.setCellStyle(cellStyles[5]);
            cell = row.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()));
            cell.setCellStyle(cellStyles[6]);
            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());
            cell.setCellStyle(cellStyles[7]);
        }
        // 导出workbook
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出库表.xlsx");

    }

    @RequestMapping(value = "/printExcelMillion", name = "百万数据导出")
    public void printExcelMillion(String inputDate) throws IOException {
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoByShipTime(inputDate, getCompanyId());

        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("出库表");
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        Row row = sheet.createRow(0);
        // 设置行高
        row.setHeightInPoints(36);
        Cell cell = row.createCell(1);
        String dateStr = inputDate.replaceAll("-0", "年").replaceAll("-", "年");
        cell.setCellValue(dateStr + "月出库表");
        cell.setCellStyle(bigTitle(workbook));

        // 设置表头（第2行标题）
        Row row2 = sheet.createRow(1);
        // 调整列宽
        sheet.setColumnWidth(1,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(2,16*256);
        sheet.setColumnWidth(3,26*256);
        sheet.setColumnWidth(4,16*256);
        sheet.setColumnWidth(5,16*256);
        sheet.setColumnWidth(6,16*256);
        sheet.setColumnWidth(7,16*256);
        sheet.setColumnWidth(8,16*256);

        String[] title = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        // 设置表头（第2行标题）
        row = sheet.createRow(1);
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i + 1);
            cell.setCellValue(title[i]);
        }

        int r = 2;
        for (int n = 0; n < 6000; n++) {
            for (int i = 0; i < contractProductVoList.size(); i++) {
                row = sheet.createRow(r);
                ContractProductVo contractProductVo = contractProductVoList.get(i);

                cell = row.createCell(1);
                cell.setCellValue(contractProductVo.getCustomName());
                cell = row.createCell(2);
                cell.setCellValue(contractProductVo.getContractNo());
                cell = row.createCell(3);
                cell.setCellValue(contractProductVo.getProductNo());
                cell = row.createCell(4);
                cell.setCellValue(contractProductVo.getCnumber());
                cell = row.createCell(5);
                cell.setCellValue(contractProductVo.getFactoryName());
                cell = row.createCell(6);
                cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()));
                cell = row.createCell(7);
                cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()));
                cell = row.createCell(8);
                cell.setCellValue(contractProductVo.getTradeTerms());
                r ++;
            }
        }
        // 导出workbook
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出库表.xlsx");

    }

    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }
}
